//
//  Global.swift
//  Swift-Codedase
//
//  Created by 徐先生 on 2023/2/24.
//

import Foundation
import SwiftyUserDefaults

let xScreenW = UIScreen.main.bounds.width
let xScreenH = UIScreen.main.bounds.height

/// 是否iPhoneX系列
var xIsIphoneX: Bool {
    get {
        if xScreenW > 736 {
            return true
        } else {
            return false
        }
    }
}

/// 顶部安全高度
let xIphoneTopSafeHeight = UIDevice.topSafeHeight
/// 底部安全区域高度
let xIphoneBottomSafeHeight = UIDevice.bottomSafeHeight
/// 顶部状态栏高度（包括安全区）
let xIphoneStatusBarHeight = UIDevice.statusBarHeight
/// 导航栏高度
let xIphoneNavBarHeight = UIDevice.navBarHeight
/// 状态栏+导航栏的高度
let xIphoneNavStatusBarHeight = UIDevice.navBarFullHeight
/// 底部导航栏高度
let xIphoneTabBarHeight = UIDevice.tabBarHeight
/// 底部导航栏高度（包括安全区）
let xIphoneTabBarSafeHeight = UIDevice.tabBarFullHeight



/// 获取当前控制器
public var currentController: UIViewController? {
    UIViewController.sg.currentViewController
}

// MARK: - 当前window
public var xKeyWindow: UIWindow {
    UIWindow.sg.keyWindow
}

// 获取主 window view
public var xKeyWindowView: UIView {
    var window = xKeyWindow
    if window.windowLevel != UIWindow.Level.normal {
        if let windowArray = UIApplication.shared.connectedScenes
            .map({ $0 as? UIWindowScene })
            .compactMap({ $0 })
            .first?.windows {
            for tempWin in windowArray {
                if tempWin.windowLevel == UIWindow.Level.normal {
                    window = tempWin
                    break
                }
            }
        }
    }
    return window
}


// MARK: - print
func xLog<T>(_ message: T, file: String = #file, function: String = #function, lineNumber: Int = #line) {
#if DEBUG
    // 1.获取文件名,包含后缀名
    let name = (file as NSString).lastPathComponent
    // 1.1 切割文件名和后缀名
    let fileArray = name.split(separator: ".")
    // 1.2 获取文件名
    let fileName = fileArray[0]
    let dateformatter = DateFormatter()
    // dateformatter.dateFormat = "YYYY-MM-dd HH:mm:ss sss"
    dateformatter.dateFormat = "HH:mm:ss sss"
    let time = dateformatter.string(from: Date())
    // print("\(String(describing: time))-[\(fileName)_funciton:\(function)_line:\(lineNumber)]- \(message)")
    // print("\(String(describing: time)) \(fileName) [line:\(lineNumber)] \(message)")
    //↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
    //↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑
    //------------------------------
    //------------------------------
    print("\n--------------Log-------------\n\(String(describing: time))\t\(fileName)\t[line:\(lineNumber)]\t\(function)\n\(message)\n------------------------------")
#endif
}

// MARK: - DefaultsKeys
extension DefaultsKeys {
    
    // MARK: 系统语言
    var language: DefaultsKey<String?> { .init("language", defaultValue: "zh")}
    // 黑暗模式
    var dartMode: DefaultsKey<Int> {.init("dartMode", defaultValue: 0)}
    
    // MARK: 用户信息
    var token: DefaultsKey<String> { .init("token", defaultValue: "")}
    var userId: DefaultsKey<Int> { .init("userId", defaultValue: 0)}
    
    /// 用户身份 id
    var identityId: DefaultsKey<Int> { .init("identityId", defaultValue: 0)}
    var mobile: DefaultsKey<String> { .init("mobile", defaultValue: "")}
    var avatar: DefaultsKey<String> { .init("avatar", defaultValue: "")}
    var country: DefaultsKey<Int> { .init("country", defaultValue: 0)}
    
    var username: DefaultsKey<String> { .init("username", defaultValue: "")}
    var usernameRu: DefaultsKey<String> { .init("usernameRu", defaultValue: "")}
    
    /// 注册 邀请吗
    var inviterCode: DefaultsKey<String> { .init("inviterCode", defaultValue: "")}
    
    
    // 微信openid
    var wxOpenid: DefaultsKey<String> { .init("wxOpenid", defaultValue: "")}
    // 微信unionid
    var wxUnionid: DefaultsKey<String> { .init("wxUnionid", defaultValue: "")}
    var wxAccessToken: DefaultsKey<String> { .init("wxAccessToken", defaultValue: "")}
    var wxRefreshToken: DefaultsKey<String> { .init("wxRefreshToken", defaultValue: "")}
    
    // 苹果ID 苹果登录
    var appleId: DefaultsKey<String> { .init("appleId", defaultValue: "")}
    
    
    // 记录最后一次获取验证码的时间戳
    var captchaDate: DefaultsKey<Int> { .init("captchaDate", defaultValue: 0)}
    
    /// true: 第一次安装，false：非第一次安装
    var isFirstInstall: DefaultsKey<Bool> { .init("isFirstInstall", defaultValue: true)}
    
    
    static func clearAllKeys() {
        Defaults.remove(\.language)
        Defaults.remove(\.dartMode)
        
        Defaults.remove(\.token)
        Defaults.remove(\.userId)
        Defaults.remove(\.appleId)
        
        Defaults.remove(\.captchaDate)
    }
    
}


class Global {
    static var isDark: Bool {
        if let style = UserInterfaceStyle(rawValue: Defaults[\.dartMode]) {
            switch style {
            case .system:
                if UITraitCollection.current.userInterfaceStyle == .dark {
                    return true
                }
            case .light:
                return false
            case .dark:
                return true
            }
        }
        return false
    }
}

// MARK: - 本地化
/// 本地化文件名
enum LocalizedName: String {
    /// 登录
    case login = "LocalizableLogin"
    /// 首页
    case home = "LocalizableHome"
    /// 商城
    case store = "LocalizableStore"
    /// 视频通话
    case call = "LocalizableCall"
    /// 直播
    case live = "LocalizableLive"
    /// 翻译
    case tran = "LocalizableTranslator"
}

/// 本地化文件名使用扩展
extension String {
    
    func localized(_ name: LocalizedName) -> String {
        return localized(using: name.rawValue, in: .main)
    }
    
    func localizedFormat(arguments: CVarArg..., name: LocalizedName) -> String {
        return String(format: localized(name), arguments)
    }
}
